import { defineStore } from 'pinia'
import * as userApi from '@/api/user'
import type { SysUser } from '@/types/user'
import type { PageQuery } from '@/types/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    userList: [] as SysUser[],
    userDetail: null as SysUser | null,
    loading: false,
    pagination: {
      total: 0,
      current: 1,
      pageSize: 10
    }
  }),
  
  actions: {
    // 获取用户列表
    async getUserList(params?: Record<string, any>) {
      this.loading = true
      try {
        const res = await userApi.getUserList(params)
        this.userList = res
        return res
      } finally {
        this.loading = false
      }
    },
    
    // 分页获取用户列表
    async getUserPage(params: PageQuery & Record<string, any>) {
      this.loading = true
      try {
        const res = await userApi.getUserPage(params)
        this.userList = res.rows || []
        this.pagination = {
          total: res.total || 0,
          current: params.pageNum || 1,
          pageSize: params.pageSize || 10
        }
        return res
      } finally {
        this.loading = false
      }
    },
    
    // 获取用户详情
    async getUserDetail(userId: number) {
      this.loading = true
      try {
        const res = await userApi.getUserDetail(userId)
        this.userDetail = res
        return res
      } finally {
        this.loading = false
      }
    },
    
    // 新增用户
    async addUser(data: Partial<SysUser>) {
      this.loading = true
      try {
        return await userApi.addUser(data)
      } finally {
        this.loading = false
      }
    },
    
    // 修改用户
    async updateUser(data: Partial<SysUser>) {
      this.loading = true
      try {
        return await userApi.updateUser(data)
      } finally {
        this.loading = false
      }
    },
    
    // 删除用户
    async deleteUser(userId: number) {
      this.loading = true
      try {
        return await userApi.deleteUser(userId)
      } finally {
        this.loading = false
      }
    },
    
    // 重置状态
    resetState() {
      this.userList = []
      this.userDetail = null
      this.pagination = {
        total: 0,
        current: 1,
        pageSize: 10
      }
    }
  }
})
